//
//  MCStoreDeliveryViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/27.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit
import MapKit


class MCStoreDeliveryViewController: MCViewController {

    
    var storeDict : [String : Any] = [:]
    
    // 到店取
    private var installBeginTime = ""
    private var installEndTime = ""

    // 及时送
    private var flashExpressBeginTime = ""
    private var flashExpressEndTime = ""
    private var distance : String = ""
    private var flashExpressCost : NSNumber = 0
    private var flashExpressTime : String = ""  // 及时送的送达时间

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    @objc func rightItemClicked() {
        let vc = MCServiceAgreementViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    // 到店取的事件
    @objc func storeDeliverySwitchEvent() {
        var status = 1
        if storeView.deliverySwitch.isOn {
            status = 1
        } else {
            status = 2
        }
        
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            "openInstall" : status
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_changeDistribution, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            var str = ""
            if status == 1 {
                str = "开启到店取"
            } else {
                str = "关闭到店取"
            }
            
            MCHUD_text(message: str, view: self.view, delay: 1.5)
        }, dislike: { (response) in }) { (error) in }
    }
    
    @objc func storeShowSettingViewEvent() {
        if !storeView.deliverySwitch.isOn {
            MCHUD_text(message: "请先打开到店取功能再进行设置", view: self.view, delay: 1.5)
            return
        }
        view.addSubview(storeSettingView)
        storeSettingView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
    }
    
    @objc func storeSettingViewConfirmEvent() {
        
        let begin = MCDateToNSString(date: storeSettingView.beginDatePicker.date as NSDate)
        let end = MCDateToNSString(date: storeSettingView.endDatePicker.date as NSDate)

        let para = [
            "installBeginTime" : begin,
            "installEndTime" : end,
            "storeId" : MCUserinfo_getStoreId(),
            "type" : 2
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_updateDistributionTime, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            
            self.storeSettingView.removeFromSuperview()
            MCHUD_text(message: "设置到店取内容成功", view: self.view, delay: 1.5)
           

            
            // 修改到店取时间
            self.installBeginTime = begin.MCString_prefix(index: 5)
            self.installEndTime = end.MCString_prefix(index: 5)
            let openInstallInfoOne = self.installBeginTime.MCString_prefix(index: 5) + "~" + self.installEndTime.MCString_prefix(index: 5)
            self.storeView.infoArray = [openInstallInfoOne]
                        
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    
    
    
    // 及时送的点击事件
    @objc func inTimeDeliverySwitchEvent() {
        var status = 1
        if inTimeView.deliverySwitch.isOn {
            status = 1
        } else {
            status = 2
        }
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            "openFlashExpress" : status
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_changeDistribution, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            var str = ""
            if status == 1 {
                str = "开启及时送"
            } else {
                str = "关闭及时送"
            }
            
            MCHUD_text(message: str, view: self.view, delay: 1.5)
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    @objc func inTimeShowSettingViewEvent() {
        if !inTimeView.deliverySwitch.isOn {
            MCHUD_text(message: "请先打开及时送功能再进行设置", view: self.view, delay: 1.5)
            return
        }
        view.addSubview(inTimeSettingView)
        inTimeSettingView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
    }
    
    @objc func inTimeSettingViewConfirmEvent() {
        
        let begin = MCDateToNSString(date: inTimeSettingView.beginDatePicker.date as NSDate)
        let end = MCDateToNSString(date: inTimeSettingView.endDatePicker.date as NSDate)
        let distance = inTimeSettingView.firstStep_distanceView.countTextField.text ?? "1"
        let cost = Int(inTimeSettingView.secondStepView.countTextField.text!)!*100
        let arriveTime = inTimeSettingView.firstStep_timeView.countTextField.text ?? "1"
        
        
        
        
        let para = [
            "flashExpressBeginTime" : begin,
            "flashExpressEndTime" : end,
            "storeId" : MCUserinfo_getStoreId(),
            "type" : 1,
            "distance" : distance,
            "flashExpressTime" : arriveTime,
            "flashExpressCost" : cost
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_updateDistributionTime, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            
            self.inTimeSettingView.removeFromSuperview()
            
            MCHUD_text(message: "设置及时送内容成功", view: self.view, delay: 1.5)
           
            
            // 修改内容
            let inTimeStr = distance + "km  " + begin.MCString_prefix(index: 5) + "~" + end.MCString_prefix(index: 5) + "  " + MCString_judgemantDecimalsIsZero(figure: cost) + "  " + arriveTime + "分钟"
//            self.inTimeView.inifoLabel.text = inTimeStr
            
            
            // 及时送
            self.distance = distance
            self.flashExpressCost = NSNumber.init(value: cost)
            self.flashExpressBeginTime = begin
            self.flashExpressEndTime = end
            self.flashExpressTime = arriveTime
            
            
            let openFlashExpressStrOne = distance + "km"
            let openFlashExpressStrTwo = self.flashExpressTime + "分钟"
            let openFlashExpressStrThree = MCString_judgemantDecimalsIsZero(figure: self.flashExpressCost.intValue)
            
            let openFlashExpressStrFour = self.flashExpressBeginTime.MCString_prefix(index: 5) + "~" + self.flashExpressEndTime.MCString_prefix(index: 5)
            
            self.inTimeView.infoArray = [openFlashExpressStrOne,openFlashExpressStrTwo,openFlashExpressStrThree,openFlashExpressStrFour]
            
            
            
            
            
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    
    @objc func expressDeliverySwitchEvent() {
        var status = 1
        if expressView.deliverySwitch.isOn {
            status = 1
        } else {
            status = 2
        }
        
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            "openExpress" : status
            ] as [String : Any]

        MCNetwork_post(url: JAVA_changeDistribution, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            
            var str = ""
            if status == 1 {
                str = "开启快递送"
            } else {
                str = "关闭快递送"
            }
            
            MCHUD_text(message: str, view: self.view, delay: 1.5)
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    

    // MARK: - Network
    func sendNetworking() {
        
        if storeDict.values.count == 0 {
            return
        }
    
        var store_tel = storeDict["tel"] as! String

        // 店铺信息
        let store_province = storeDict["province"] as! String
        let store_city = storeDict["city"] as! String
        let store_area = storeDict["area"] as! String
        let store_address = storeDict["address"] as! String
        let store_lat = storeDict["lat"] as! String
        let store_lon = storeDict["lon"] as! String
        if store_tel.count == 0 { store_tel = "暂无电话" }
        mapView.mapPhoneLabel.text = store_tel
        mapView.mapAddressLabel.text = store_province + store_city + store_area + store_address
        let latitude = CLLocationDegrees.init(Double(store_lat)!)
        let longitude = CLLocationDegrees.init(Double(store_lon)!)
        let centerCoord = CLLocationCoordinate2D.init(latitude: latitude, longitude: longitude)
        let span = MKCoordinateSpanMake(0.162493481087147, 0.10857004327103)
        let region = MKCoordinateRegionMake(centerCoord, span)
        mapView.mapView.setRegion(region, animated: true)

        
        
        
        
        // 及时送
        let openFlashExpress = storeDict["openFlashExpress"] as! NSNumber
        let distance = storeDict["distance"] as! NSNumber
        self.distance = distance.stringValue
        flashExpressCost = storeDict["flashExpressCost"] as! NSNumber
        flashExpressBeginTime = storeDict["flashExpressBeginTime"] as! String
        flashExpressEndTime = storeDict["flashExpressEndTime"] as! String
        let flashExpressTime = storeDict["flashExpressTime"] as! NSNumber
        self.flashExpressTime = flashExpressTime.stringValue
        inTimeView.deliverySwitch.setOn(openFlashExpress.boolValue, animated: false)
        
        
        let openFlashExpressStrOne = self.distance + "km"
        let openFlashExpressStrTwo = self.flashExpressTime + "分钟"
        let openFlashExpressStrThree = MCString_judgemantDecimalsIsZero(figure: flashExpressCost.intValue)
        
        let openFlashExpressStrFour = flashExpressBeginTime.MCString_prefix(index: 5) + "~" + flashExpressEndTime.MCString_prefix(index: 5)

        inTimeView.infoArray = [openFlashExpressStrOne,openFlashExpressStrTwo,openFlashExpressStrThree,openFlashExpressStrFour]
    

        // 到店取
        let openInstall = storeDict["openInstall"] as! NSNumber
        installBeginTime = storeDict["installBeginTime"] as! String
        installEndTime = storeDict["installEndTime"] as! String
        storeView.deliverySwitch.setOn(openInstall.boolValue, animated: false)
        let openInstallInfoOne = installBeginTime.MCString_prefix(index: 5) + "~" + installEndTime.MCString_prefix(index: 5)
        storeView.infoArray = [openInstallInfoOne]
        
        
        // 快递送
        let openExpress = storeDict["openExpress"] as! NSNumber
        let priceNoFreight = storeDict["priceNoFreight"] as! NSNumber
        
        expressView.deliverySwitch.setOn(openExpress.boolValue, animated: false)
        let openExpressInfoOne = "满" + MCString_judgemantDecimalsIsZero(figure: priceNoFreight.intValue) + "包邮"
        
        expressView.infoArray = [openExpressInfoOne]

    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "配送方式"
        self.view.backgroundColor = UIColor.MCGray_light
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("服务协议", target: self, selector: #selector(rightItemClicked))
    }
    
    func MCDateToNSString(date:NSDate) -> String {
        let dateFormat = DateFormatter.init()
        dateFormat.dateFormat = "HH:mm:ss"
        return dateFormat.string(from: date as Date)
    }
    
    func initUI() {
        
        view.addSubview(expressView)
        expressView.snp.remakeConstraints { (make) ->Void in
            
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(70)
        }

        
        view.addSubview(storeView)
        storeView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(expressView.snp.bottom)
            make.height.equalTo(70)
        }
        
        
        view.addSubview(inTimeView)
        inTimeView.snp.remakeConstraints { (make) ->Void in
            
            make.left.right.equalTo(0)
            make.top.equalTo(storeView.snp.bottom)
            make.height.equalTo(70)
        }
        
        

        
        view.addSubview(mapView)
        mapView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(inTimeView.snp.bottom).offset(7)
            make.height.equalTo(MCScreenWidth * 0.8 + 75)
        }
    }

    // MARK: - Setter & Getter
    lazy var inTimeView: MCStoreDeliveryItemView = {
        let view = MCStoreDeliveryItemView()
        view.deliveryButton.setImage(#imageLiteral(resourceName: "Order_inTimeToSend"), for: UIControlState.normal)
        view.deliveryButton.setTitle("  及时送", for: UIControlState.normal)
        view.deliverySwitch.addTarget(self, action: #selector(inTimeDeliverySwitchEvent), for: UIControlEvents.valueChanged)
        view.showSettingButton.addTarget(self, action: #selector(inTimeShowSettingViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    lazy var expressView: MCStoreDeliveryItemView = {
        let view = MCStoreDeliveryItemView()
        view.deliveryButton.setImage(#imageLiteral(resourceName: "Order_express"), for: UIControlState.normal)
        view.deliveryButton.setTitle("  快递送", for: UIControlState.normal)
        view.editImageView.isHidden = true
        view.deliverySwitch.addTarget(self, action: #selector(expressDeliverySwitchEvent), for: UIControlEvents.valueChanged)
        return view
    }()

    lazy var storeView: MCStoreDeliveryItemView = {
        let view = MCStoreDeliveryItemView()
        view.deliveryButton.setImage(#imageLiteral(resourceName: "Order_store"), for: UIControlState.normal)
        view.deliveryButton.setTitle("  到店取", for: UIControlState.normal)
        view.deliverySwitch.addTarget(self, action: #selector(storeDeliverySwitchEvent), for: UIControlEvents.valueChanged)
        view.showSettingButton.addTarget(self, action: #selector(storeShowSettingViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()

    lazy var mapView: MCStoreMapView = {
        let view = MCStoreMapView()
        return view
    }()
    
    lazy var storeSettingView: MCDeliveryStoreView = {
        let view = MCDeliveryStoreView()
        view.titleLabel.text = "设置到店取"
        
        let dateFormat = DateFormatter.init()
        dateFormat.dateFormat = "HH:mm:ss"
        let dateBegin = dateFormat.date(from: installBeginTime)
        let dateEnd = dateFormat.date(from: installEndTime)
        view.beginDatePicker.setDate(dateBegin!, animated: true)
        view.endDatePicker.setDate(dateEnd!, animated: true)
        
        view.confirmButton.addTarget(self, action: #selector(storeSettingViewConfirmEvent), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    
    lazy var inTimeSettingView: MCDeliveryInTimeView = {
        let view = MCDeliveryInTimeView()
        view.titleLabel.text = "设置及时送"
        
        let dateFormat = DateFormatter.init()
        dateFormat.dateFormat = "HH:mm:ss"
        let dateBegin = dateFormat.date(from: flashExpressBeginTime)
        let dateEnd = dateFormat.date(from: flashExpressEndTime)
        view.beginDatePicker.setDate(dateBegin!, animated: true)
        view.endDatePicker.setDate(dateEnd!, animated: true)
        
        view.firstStep_distanceView.countTextField.text = self.distance
        view.firstStep_timeView.countTextField.text = flashExpressTime
        view.secondStepView.countTextField.text = String(flashExpressCost.intValue/100)
        
        
        view.confirmButton.addTarget(self, action: #selector(inTimeSettingViewConfirmEvent), for: UIControlEvents.touchUpInside)
        return view
    }()
}
